import React from "react";
import { Button, Popover } from "antd-mobile";
import { isFunction } from "src/utils/index";
import PropTypes from "prop-types";

function Btns(props) {
    const { btns, className, source, position, ...restProps } = props;
    return (
        <div
            className={"btns " + (className || "")}
            style={{ justifyContent: `flex-${position === "left" ? "start" : "end"}` }}
        >
            {btns.map((item, i) => {
                const label = isFunction(item.label) ? item.label() : item.label;
                if (
                    item.hidden &&
                    ((isFunction(item.hidden) && item.hidden(source)) ||
                        (!isFunction(item.hidden) && item.hidden))
                )
                    return;
                let btn = (
                    <Button
                        type="primary"
                        key={item.key}
                        onClick={e => {
                            e.stopPropagation();
                            item.fn(source);
                        }}
                        disabled={isFunction(item.disabled) ? item.disabled(source) : item.disabled}
                        size="small"
                        color="primary"
                        fill="solid"
                        {...restProps}
                    >
                        {label}
                    </Button>
                );
                if (item.Popover) {
                    return (
                        <Popover key={item.key} content={item.label} trigger="click">
                            {btn}
                        </Popover>
                    );
                }
                return btn;
            })}
        </div>
    );
}

Btns.propTypes = {
    btns: PropTypes.arrayOf(
        PropTypes.shape({
            label: PropTypes.string,
            key: PropTypes.string.isRequired,
            fn: PropTypes.func,
            hidden: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
        }),
    ),
    props: PropTypes.object,
    className: PropTypes.string,
    source: PropTypes.object,
    position: PropTypes.oneOf(["left", "right"]),
};

export default Btns;
